<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="hardcode2013.*" %>
<%@ page import="java.util.List" %>

<html>
	<head>
		<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
	</head>
	
	<body>
	
	<%@include file="include_header.jsp" %>
	
	<%
		String partner = request.getParameter("partner");
		String itemKeyStr = request.getParameter("item_key");
		
		if (profile != null && partner != null) {
		
			ItemProfile item = null;
			if (itemKeyStr != null)
				item = ItemServ.getItemProfile(itemKeyStr);
				
			List<MessageProfile> msgList = MailServ.getMessages(profile.getUsername(), partner, itemKeyStr);
	
			String legend = "Conversation with " + "<b>" + EncodeUtil.encodeHtml(partner) + "</b>" +
				" (Item: " + (itemKeyStr != null ? EncodeUtil.encodeHtml(ItemServ.getItemTitle(itemKeyStr)) +
				", Orignal Price: " + EncodeUtil.encodeHtml(msgList.get(msgList.size() - 1).getItemPrice()) : "-") + ")";
			
			%>
			<fieldset>
				<legend><%= legend %></legend>

				<form action="/mail" method="post">
					<% if (item != null) { %><input type="hidden" name="item_key" value="<%= EncodeUtil.encodeHtml(item.getKeyStr()) %>"><% } %>
					Recipient: <input type="hidden" name="recipient" value="<%= EncodeUtil.encodeHtml((item == null || item.getSeller().equals(profile.getUsername()) ? partner : item.getSeller())) %>"><br>
					Title: <input type="text" name="title" <%= (item != null ? "value=\"" + "RE: " + EncodeUtil.encodeHtml(item.getTitle()) + "\"" : "") %>><br>
					Content:<br><textarea name="content" rows="5" cols="50"></textarea><br>	      
					<input type="hidden" name="action" value="create_message">
					<input type="hidden" name="redirect" value="<%= EncodeUtil.encodeHtml("/conversation.jsp" + "?partner=" + partner + (itemKeyStr != null ? "&item_key=" + itemKeyStr : "")) %>">
					<input type="hidden" name="auth_key" value="<%= SessionUtil.getAuthKey(request) %>">
					<input type="submit" value="Reply" />
				</form>
				
				<%
				for (MessageProfile m : msgList) {
					%>
					<div>
						<b>[<%=EncodeUtil.encodeHtml(m.getSender())%>] : <%= (m.getTitle().trim().isEmpty() ? "-" : EncodeUtil.encodeHtml(m.getTitle())) %></b><br>
						<%=EncodeUtil.encodeHtml(m.getContent()).replaceAll("\n", "<br>")%>
					</div>
					<br>
					<%
				}
				%>
			</fieldset>
			<%
		}
		%>
	</body>
</html>